Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath({'Ext.ux' : 'extjs4/ux'});
Ext.require([
             'Ext.grid.*',
             'Ext.data.*',
             'Ext.ux.grid.FiltersFeature',
             'Ext.toolbar.Paging',
             'Ext.ux.ajax.JsonSimlet',
             'Ext.ux.ajax.SimManager'      
]);
Ext.define('TS.controller.RpAPayCheckEditors',{
	extend: 'Ext.app.Controller',
	models:['rp.ArpBillModel','rp.RpBillModel','rp.ArpBillTransferModel'],
	views:['rp.RpAPayCheckEditor'],
	init:function() {
		this.control({
			'rpapaycheckeditor triggerfield[name=customer]':{specialkey:this.onSearchCust,change:this.onClearCust},
			'rpapaycheckeditor button[action=search]':{click:this.onSearch},
			'rpapaycheckeditor button[action=check]':{click:this.onCheckBill}
		});
	},
	onSearch:function(button) {
//		var begDate = button.up('panel').down('datefield[name=begDate]').getRawValue();
//		var endDate = button.up('panel').down('datefield[name=endDate]').getRawValue();
		var custId = button.up('panel').down('hiddenfield[name=custId]').getValue();
		//var grid = button.up('form').up('panel').down('grid');
		var tab = button.up('form').up('panel').down('tabpanel');
		var panel = tab.getActiveTab();
		if(panel.itemId == 'paybillsettle') {
			var paybillGrid = panel.items.get(0);
			this.doSearchPayBill(paybillGrid,custId);
			var apaybillGrid = panel.items.get(2);
			this.doSearchAPayBill(apaybillGrid,custId);
		} else if(panel.itemId == 'refundbillsettle') {
			var refundbillGrid = panel.items.get(0);
			this.doSearchRefundPayBill(refundbillGrid,custId);
			var paybillGrid = panel.items.get(2);
			this.doSearchPayBill(paybillGrid,custId);
		} else if(panel.itemId == 'offsetsettle') {
			var apaybillGrid = panel.items.get(0);
			this.doSearchAPayBill(apaybillGrid,custId);
			var arecbillGrid = panel.items.get(2);
			this.doSearchARecBill(arecbillGrid,custId);
		} else if(panel.itemId == 'transfersettle') {
			var apaybillGrid = panel.items.get(0);
			this.doSearchAPayBillForTransfer(apaybillGrid,custId);
		}
	},
	doSearchPayBill:function(grid,custId) {
		var store = Ext.create('Ext.data.Store',{
			model:'TS.model.rp.RpBillModel',
			proxy:{
				url:'rp/apaycheck/getUnSettlePayBill.do',
				type:'ajax',
				reader:{
					type:'json',
					root:''
				}
			},
			autoLoad:false
		});
		store.load({
			params:{custId:custId},
			callback:function() {
				grid.reconfigure(store);
			}
		});
	},
	doSearchARecBill:function(grid,custId) {
		var store = Ext.create('Ext.data.Store',{
			model:'TS.model.rp.ArpBillModel',
			proxy:{
				url:'rp/apaycheck/getUnSettleARecBill.do',
				type:'ajax',
				reader:{
					type:'json',
					root:''
				}
			},
			autoLoad:false
		});
		store.load({
			params:{custId:custId},
			callback:function() {
				grid.reconfigure(store);
			}
		});
	},
	doSearchAPayBillForTransfer:function(grid,custId) {
		var store = Ext.create('Ext.data.Store',{
			model:'TS.model.rp.ArpBillTransferModel',
			proxy:{
				url:'rp/apaycheck/getUnSettleAPayBill.do',
				type:'ajax',
				reader:{
					type:'json',
					root:''
				}
			},
			autoLoad:false
		});
		store.load({
			params:{custId:custId},
			callback:function() {
				grid.reconfigure(store);
			}
		});
	},
	doSearchRefundPayBill:function(grid,custId){
		var store = Ext.create('Ext.data.Store',{
			model:'TS.model.rp.RpBillModel',
			proxy:{
				url:'rp/apaycheck/getUnSettleRefundPayBill.do',
				type:'ajax',
				reader:{
					type:'json',
					root:''
				}
			},
			autoLoad:false
		});
		store.load({
			params:{custId:custId},
			callback:function() {
				grid.reconfigure(store);
			}
		});
	},
	doSearchAPayBill:function(grid,custId) {
		var store = Ext.create('Ext.data.Store',{
			model:'TS.model.rp.ArpBillModel',
			proxy:{
				url:'rp/apaycheck/getUnSettleAPayBill.do',
				type:'ajax',
				reader:{
					type:'json',
					root:''
				}
			},
			autoLoad:false
		});
		store.load({
			params:{custId:custId},
			callback:function() {
				grid.reconfigure(store);
			}
		});
	},
	onSearchCust:function(field,e) {
		var custIdField = field.up('panel').down('hiddenfield[name=custId]');
		if(e.getKey() == e.ENTER && field.value != '') {
		    	var view=Ext.create('TS.view.base.CustomerSearchDialog');
		    	view.setVal(field.value);
		    	view.on({
				    selected: function(records){
				    	if(records.length == 0) {
				    		Ext.MessageBox.alert('ThinkGsp','未检索到任何客户信息!');
				    	} else {
					    	custIdField.setValue(records[0].get('customerId'));
					    	field.setValue('[' + records[0].get('customerCode') + ']' + records[0].get('customerName'));
				    	}
				    },
				    scope: this
				});
		    	view.show();	
	    }
	},
	onClearCust:function(field,e) {
		var custIdField = field.up('panel').down('hiddenfield[name=custId]');
		if(field.value == '') {
			//var custIdField = field.up('panel').down('hiddenfield[name=custId]');
			custIdField.setValue(null);
		}
	},
	onCheckBill:function(button) {
		var tab = button.up('panel').down('tabpanel');
		var panel = tab.getActiveTab();
		if(panel.itemId == 'paybillsettle') {
			var paybillGrid = panel.items.get(0);
			var apaybillGrid = panel.items.get(2);
			this.doPayBillCheck(paybillGrid,apaybillGrid);
		} else if(panel.itemId == 'refundbillsettle') {
			var refundbillGrid = panel.items.get(0);
			var paybillGrid = panel.items.get(2);
			this.doRefundBillCheck(refundbillGrid,paybillGrid);
		} else if(panel.itemId == 'offsetsettle') {
			var apaybillGrid = panel.items.get(0);
			var arecbillGrid = panel.items.get(2);
			this.doOffsetCheck(apaybillGrid,arecbillGrid);
		} else if(panel.itemId == 'transfersettle') {
			var apaybillGrid = panel.items.get(0);
			this.doTransferCheck(apaybillGrid);
		}
	},
	doPayBillCheck:function(paygrid,apaygrid) {
		var paybills = paygrid.getSelectionModel().getSelection();
		var apaybills = apaygrid.getSelectionModel().getSelection();
		var paybillcheckamt = 0;
		var apaybillcheckamt = 0;
		
		var rbs = new Array(paybills.length);
		for(var i = 0; i < paybills.length; i++) {
			paybillcheckamt += paybills[i].get('currentCheckAmount');
			rbs[i] = paybills[i].getData(false);
		}
		var arbs = new Array(apaybills.length);
		for(var i = 0; i < apaybills.length; i++) {
			apaybillcheckamt += apaybills[i].get('currentCheckAmount');
			arbs[i] = apaybills[i].getData(false);
		}
		if(paybillcheckamt != apaybillcheckamt) {
			//console.debug('RecBill check amount validate :[recbillcheckamt:' + recbillcheckamt + ';arecbillcheckamt:' + arecbillcheckamt + '].');
			Ext.Msg.show({
				title:'警告',
				msg:'付款单单据的核销金额总和:' + paybillcheckamt + '与应付单的核销金额总和:' + apaybillcheckamt + '不符!',
				buttons:Ext.Msg.OK,
				icon:Ext.Msg.ERROR
			});
			return false;
		}
		var data = {payBills:rbs,apayBills:arbs};
		Ext.Ajax.request({
			url:'rp/apaycheck/checkForPayBill.do',
			method:'POST',
			jsonData:data,
			success:function(response) {
		    	var data=Ext.decode(response.responseText);
		    	if(data.success==true){
		    		Ext.MessageBox.show({
		    			title:'ThinkGsp',
		    			msg:data.msg,
		    			buttons:Ext.Msg.OK,
		    			icon:Ext.Msg.INFO,
		    			fn:function(buttonId) {
				    		var searchbtn = paygrid.up('panel').up('tabpanel').up('panel').down('form').down('button[action=search]');
				    		this.onSearch(searchbtn);
		    			},
		    			scope:this
		    		});
		    	} else {
		    		Ext.MessageBox.show({
		    			title:'错误',
		    			msg:data.msg,
		    			buttons:Ext.Msg.OK,
		    			icon:Ext.Msg.ERROR
		    		});			    		
		    	}
			},
			scope:this
		});
	},
	doRefundBillCheck:function(refundgrid,paygrid) {
		var selectedrefundbills = refundgrid.getSelectionModel().getSelection();
		var selectedpaybills = paygrid.getSelectionModel().getSelection();
		var refundbillcheckamt = 0;
		var paybillcheckamt = 0;
		
		var refundbills = new Array(selectedrefundbills.length);
		for(var i = 0; i < selectedrefundbills.length; i++) {
			refundbillcheckamt += selectedrefundbills[i].get('currentCheckAmount');
			refundbills[i] = selectedrefundbills[i].getData(false);
		}
		var paybills = new Array(selectedpaybills.length);
		for(var i = 0; i < selectedpaybills.length; i++) {
			paybillcheckamt += selectedpaybills[i].get('currentCheckAmount');
			paybills[i] = selectedpaybills[i].getData(false);
		}
		if((refundbillcheckamt + paybillcheckamt) != 0) {
			//console.debug('RecBill check amount validate :[recbillcheckamt:' + recbillcheckamt + ';arecbillcheckamt:' + arecbillcheckamt + '].');
			Ext.Msg.show({
				title:'警告',
				msg:'退款单单据的核销金额总和:' + refundbillcheckamt + '与付款单的核销金额总和:' + paybillcheckamt + '不符!',
				buttons:Ext.Msg.OK,
				icon:Ext.Msg.ERROR
			});
			return false;
		}
		var data = {refundPayBills:refundbills,payBills:paybills};
		Ext.Ajax.request({
			url:'rp/apaycheck/checkForRefundPayBill.do',
			method:'POST',
			jsonData:data,
			success:function(response) {
		    	var data=Ext.decode(response.responseText);
		    	if(data.success==true){
		    		Ext.MessageBox.show({
		    			title:'ThinkGsp',
		    			msg:data.msg,
		    			buttons:Ext.Msg.OK,
		    			icon:Ext.Msg.INFO,
		    			fn:function(buttonId) {
				    		var searchbtn = paygrid.up('panel').up('tabpanel').up('panel').down('form').down('button[action=search]');
				    		this.onSearch(searchbtn);
		    			},
		    			scope:this
		    		});
		    	} else {
		    		Ext.MessageBox.show({
		    			title:'错误',
		    			msg:data.msg,
		    			buttons:Ext.Msg.OK,
		    			icon:Ext.Msg.ERROR
		    		});			    		
		    	}
			},
			scope:this
		});
	},
	doOffsetCheck:function(apaygrid,arecgrid) {
		var selectedapaybills = apaygrid.getSelectionModel().getSelection();
		var selectedarecbills = arecgrid.getSelectionModel().getSelection();
		var arecbillcheckamt = 0;
		var apaybillcheckamt = 0;
		
		var arecbills = new Array(selectedarecbills.length);
		for(var i = 0; i < selectedarecbills.length; i++) {
			arecbillcheckamt += selectedarecbills[i].get('currentCheckAmount');
			arecbills[i] = selectedarecbills[i].getData(false);
		}
		var apaybills = new Array(selectedapaybills.length);
		for(var i = 0; i < selectedapaybills.length; i++) {
			apaybillcheckamt += selectedapaybills[i].get('currentCheckAmount');
			apaybills[i] = selectedapaybills[i].getData(false);
		}
		if(arecbillcheckamt != apaybillcheckamt) {
			//console.debug('RecBill check amount validate :[recbillcheckamt:' + recbillcheckamt + ';arecbillcheckamt:' + arecbillcheckamt + '].');
			Ext.Msg.show({
				title:'警告',
				msg:'应收单的核销金额总和:' + arecbillcheckamt + '与应付单的核销金额总和:' + apaybillcheckamt + '不符!',
				buttons:Ext.Msg.OK,
				icon:Ext.Msg.ERROR
			});
			return false;
		}
		var data = {apayBills:apaybills,arecBills:arecbills};
		Ext.Ajax.request({
			url:'rp/apaycheck/checkForApayBillOffsetArecBill.do',
			method:'POST',
			jsonData:data,
			success:function(response) {
		    	var data=Ext.decode(response.responseText);
		    	if(data.success==true){
		    		Ext.MessageBox.show({
		    			title:'ThinkGsp',
		    			msg:data.msg,
		    			buttons:Ext.Msg.OK,
		    			icon:Ext.Msg.INFO,
		    			fn:function(buttonId) {
				    		var searchbtn = apaygrid.up('panel').up('tabpanel').up('panel').down('form').down('button[action=search]');
				    		this.onSearch(searchbtn);
		    			},
		    			scope:this
		    		});
		    	} else {
		    		Ext.MessageBox.show({
		    			title:'错误',
		    			msg:data.msg,
		    			buttons:Ext.Msg.OK,
		    			icon:Ext.Msg.ERROR
		    		});			    		
		    	}
			},
			scope:this
		});
	},
	doTransferCheck:function(apaygrid) {
		var selectedapaybills = apaygrid.getSelectionModel().getSelection();
		for(var i = 0; i < selectedapaybills.length; i++) {
			var chkamt = selectedapaybills[i].get('currentCheckAmount');
			var custId = selectedapaybills[i].get('transferCustId');
			if(chkamt == 0 || !custId || custId == 0) {
				Ext.Msg.show({
					title:'警告',
					msg:'请输入转出金额或者选择转出客商.',
					buttons:Ext.Msg.OK,
					icon:Ext.Msg.WARNING
				});
				return false;
			}
		}
		Ext.Msg.show({
			title:'应付款转销',
			msg:'正在提交转销请求...',
			progress:true,
			progressText: '正在准备...',
	        width:300,
		});
        var msg = '';
        var me = this;
        var f = function(v){
            return function(){
                if(v == selectedapaybills.length){
                    Ext.MessageBox.hide();
                    Ext.Msg.show({
                    	title:'ThinkGsp',
                    	msg:msg,
                    	buttons:Ext.Msg.OK,
                    	icon:Ext.Msg.INFO,
                    	fn:function(buttonId) {
                    		var searchbtn = apaygrid.up('panel').up('tabpanel').up('panel').down('form').down('button[action=search]');
                    		me.onSearch(searchbtn);
                    	}
                    });
                }else{
                    var i = v/selectedapaybills.length;
                    Ext.MessageBox.updateProgress(i, Math.round(100*i)+'% 完成');
                }
           };
        };
		for(var i = 0; i < selectedapaybills.length; i++) {
			var custId = selectedapaybills[i].get('transferCustId');
			var apaybillmodel = Ext.create('TS.model.rp.ArpBillModel');
			var apaybill = Ext.copyTo({},selectedapaybills[i].getData(false),'arpBillId,arpBillCode,arpBillType,arpBillName,billDate,funcDate,arpDate,direct,custSuppId,deptId,empId,makerId,amount,jxcBillId,fyear,period,archived,remark,checkAmount,checkStatus,currentCheckAmount');
			var data = {apayBill:apaybill,custSuppId:custId};
			Ext.Ajax.request({
				url:'rp/apaycheck/checkForApayBillTransfer.do',
				method:'POST',
				jsonData:data,
				success:function(response) {
			    	var data=Ext.decode(response.responseText);
			    	msg += '<br/>[' + apaybill.arpBillCode + ']' + data.msg;
				},
				failure:function(response) {
					msg[i] = '<br/>[' + apaybill.arpBillCode + ']转销出错!';
				},
				scope:this
			});
			setTimeout(f(i+1), i*500);
		}
	}
});	